package com.a01_2021.thousandstimes.instance.service.impl;

import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.exception.CustomExceptionType;
import com.a01_2021.thousandstimes.instance.entity.InterpolateAttachment;
import com.a01_2021.thousandstimes.instance.mapper.InterpolateAttachmentMapper;
import com.a01_2021.thousandstimes.instance.service.IInterpolateAttachmentService;
import com.a01_2021.thousandstimes.instance.service.IInterpolateService;
import com.a01_2021.thousandstimes.utils.IO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author E1xP
 * @since 2021-03-10
 */
@Service
public class InterpolateAttachmentServiceImpl extends ServiceImpl<InterpolateAttachmentMapper, InterpolateAttachment> implements IInterpolateAttachmentService {

    @Resource
    InterpolateAttachmentMapper interpolateAttachmentMapper;

    @Resource
    IInterpolateService interpolateService;

    @Value("${path.interpolateAttachmentFolder}")
    String attachmentFolder;//内推附件存储文件夹

    private List<String> expectExt;

    InterpolateAttachmentServiceImpl() {
        expectExt = new ArrayList<>();
        expectExt.add(".jpg");
        expectExt.add(".png");
        expectExt.add(".dox");
        expectExt.add(".docx");
    }

    /**
     * 用于批量添加内推附件
     *
     * @param interpolateId  内推id
     * @param attachmentList 附件URL列表
     * @throws CustomException 当内推不存在时抛出该异常
     */
    public void addAttachments(long interpolateId, List<String> attachmentList) throws CustomException {
        if (!interpolateService.isInterpolate(interpolateId)) {
            throw new CustomException(CustomExceptionType.INTERPOLATE_NOT_FOUND_ERROR, "找不到该内推");
        }
        //循环插入不为空的附件URL
        for (String item : attachmentList) {
            if (!StringUtils.isEmpty(item)) {
                interpolateAttachmentMapper.insert(new InterpolateAttachment(null, interpolateId, item));
            }
        }
    }

    @Override
    public String update(MultipartFile file, String instanceId) throws CustomException, IOException {
        String ext = IO.getExt(file, expectExt);
        String url = IO.saveFile(file, ext, "/" + attachmentFolder + "/" + instanceId);
        return "/interpolate/" + instanceId + "/" + url;
    }
}
